/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.iboss.service.sc;

import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.entity.org.OrganizationEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.RemarkOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScStatusConstant;
import net.dgg.dggcloud.service.iboss.dao.sc.InProcessDao;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProOrder;
import net.dgg.dggcloud.service.iboss.utils.DataWrap;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import net.dgg.dggcloud.service.jrcrm.service.orf.api.OrderApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @class_name: InProcessService
 * @package: net.dgg.dggcloud.service.iboss.service.sc
 * @describe: TODO 生产订单办理中-service层
 * @creat_user: 孙上峰
 * @creat_date: 2017/11/27
 * @creat_time: 15:46
 **/
@Service
public class InProcessService extends BaseService {
    @Resource
    private InProcessDao inProcessDao;
    @Resource
    private ScProOrderTimeStateService scProOrderTimeStateService;
    @Resource
    private OrderApiService orderApiService;
    @Resource
    protected MessageService messageService;
    @Resource
    private CustomerRecordService customerRecordService;
    @Autowired
    private ScProOrderService scProOrderService;
    @Autowired
    private WaitAllocationService waitAllocationService;

    /**
     * 办理中的生产订单
     *
     * @param map
     * @return
     */
    public List<Map> listInProcessByMap(Map map) {
        return inProcessDao.listInProcessByMap(map);
    }

    public Integer countInProcessByMap(Map map) {
        return inProcessDao.countInProcessByMap(map);
    }

    /**
     * 批量更新生产订单级别
     *
     * @param ids           生产订单id
     * @param productRankId 生产订单级别
     * @creat_user: 孙上峰
     */
    public void updateProductRank(String ids, String productRankId) {
        String[] idsStrArray = ids.split(",");
        for (int i = 0; i < idsStrArray.length; i++) {
            String id = idsStrArray[i];
            ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
            if (scProOrder != null) {
                scProOrder.setProductRank(productRankId);
                this.repository.saveOrUpdate(scProOrder);
            }
        }
    }

    /**
     * 生产订单转单
     *
     * @param ids  生产订单id
     * @param usid 流程人员id
     * @creat_user: 孙上峰
     */
    public void turnSingleByIds(String ids, String usid) {
        /*----------拿到流程人员信息--------*/
        User user = this.repository.get(User.class, Long.valueOf(usid));
        OrganizationEntity organizationEntity = new OrganizationEntity();
        if (user != null) {
            organizationEntity = this.repository.get(OrganizationEntity.class, Long.valueOf(user.getDeptId()));
        }
        if (organizationEntity == null) {
            //没有部门
        }
        String[] idsStrArray = ids.split(",");
        for (int i = 0; i < idsStrArray.length; i++) {
            String id = idsStrArray[i];
            ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
            if (scProOrder != null) {
                scProOrder.setStatus("SCORDER_STATUS11"); //转单待接收
                scProOrder.setFlowUserId(user.getId()); // 流程人员id
                scProOrder.setFlowUserName(user.getName()); //流程人员名称
                scProOrder.setFlowDeptId(organizationEntity.getpId()); //流程人员部门id
                scProOrder.setFlowDeptName(organizationEntity.getName()); //流程人员部门名称
            }
        }
    }

    /**
     * 根据ids拿到ScProOrder的List
     *
     * @param ids
     * @return
     */
    public List<ScProOrder> getScProOrderByIds(String ids) {
       /* 分割字符串*/
        String[] idsStrArray = ids.split(",");
        List<ScProOrder> scProOrderList = new ArrayList<>();
        for (int i = 0; i < idsStrArray.length; i++) {
            String id = idsStrArray[i];
            ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
            scProOrderList.add(scProOrder);
        }
        return scProOrderList;
    }

    /**
     * 修改生产订单信息
     *
     * @param scProOrderList
     */
    public void updateScProOrder(List<ScProOrder> scProOrderList, User user) {
        User currUser = SessionManager.getCurrentUser();
        for (ScProOrder scProOrder : scProOrderList) {
            ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
            scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_SWITCH);
            scProFlowOperating.setProProductId(scProOrder.getId());
            scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
            scProFlowOperating.setStatus(scProOrder.getStatus());
            scProFlowOperating.setOperation("转单");
            scProFlowOperating.setFlowUserId(user.getId());
            scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
            DataWrap.saveWrap(scProFlowOperating);
            scProFlowOperating.setId(this.keyWorker.nextId());
            this.repository.save(scProFlowOperating);
            this.repository.saveOrUpdate(scProOrder);
            String[] vals = new String[1];
            vals[0] = String.valueOf(scProOrder.getOrderBusinessNo());
            String tempCode = "SC_DJS_MSG";
            String tem = "订单{0}需要接收，请及时查看";
            messageService.sendMessageReady(user, currUser, vals, tempCode);//消息提醒

            //同步备注到crm
            Map recordMap = new HashMap();
            recordMap.put("tableName", ScProOrder.TABLE_NAME);
            recordMap.put("tableId", scProOrder.getId());
            recordMap.put("cusId", scProOrder.getCustomerId());
            recordMap.put("recordType", RemarkOperationConstant.REMARK_ORDER_SWITCH);//备注类型
            recordMap.put("content", "转单");//备注内容
            recordMap.put("ext3", scProOrder.getOrderBusinessNo()); //生产编号
            recordMap.put("operateUser", user.getId());//当前操作人id
            customerRecordService.saveCustomerRecord(recordMap);//写入crm

            //发送短信给流程
            this.scProOrderService.sendSmsMsgToUser(scProOrder.getWaitingReceiverId(), tempCode, scProOrder.getOrderBusinessNo());
        }
    }

    public void saveOrUpdateScProOrder(List<ScProOrder> scProOrderList) {
        for (ScProOrder scProOrder : scProOrderList) {
            this.repository.saveOrUpdate(scProOrder);
        }
    }

    /**
     * 根据userid查询人员信息
     */
    public User getUserById(String userid) {
        return this.repository.get(User.class, Long.valueOf(userid));
    }

    /**
     * 根据did查询人员部门信息
     */
    public OrganizationEntity getOrgById(String did) {
        return this.repository.get(OrganizationEntity.class, Long.valueOf(did));
    }

    /**
     * 暂缓订单
     *
     * @param id
     * @param code
     * @param remark
     */
    public void updateSuspendOrder(String id, String code, String remark) {
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
        Assert.notNull(scProOrder, "没有查询到该生产订单的信息！");
        Assert.isTrue(ScStatusConstant.ORDER_PROCESS.equals(scProOrder.getStatus()), "只有办理中的生产订单才能暂缓！");
        Assert.isTrue(scProOrder.getFlowUserId().equals(user.getId()), "只有流程人员才能进行该操作！");
        scProOrder.setStatus(ScStatusConstant.ORDERE_SUSPEND); //暂缓
        scProOrder.setNoteType(code); //备注code
        scProOrder.setNotes(remark);  //备注详情
        DataWrap.updateWraps(scProOrder);

        //保存流程操作记录
        ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
        scProFlowOperating.setProProductId(scProOrder.getId());
        scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
        scProFlowOperating.setFlowUserId(user.getId());
        scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
        scProFlowOperating.setStatus(scProOrder.getStatus());
        scProFlowOperating.setOperation("暂缓订单");
        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_SUSPEND);//暂缓订单
        DataWrap.saveWrap(scProFlowOperating);
        scProFlowOperating.setId(this.keyWorker.nextId());
        scProOrder.setFlowLatestOperationId(scProFlowOperating.getId()); //流程操作的最新id
        this.repository.save(scProFlowOperating);
        this.repository.saveOrUpdate(scProOrder);
        //同步备注到crm
        Map recordMap = new HashMap();
        recordMap.put("tableName", ScProOrder.TABLE_NAME);
        recordMap.put("tableId", scProOrder.getId());
        recordMap.put("cusId", scProOrder.getCustomerId());
        recordMap.put("recordType", RemarkOperationConstant.REMARK_ORDER_SUSPEND);//备注类型
        recordMap.put("content", remark);//备注内容
        recordMap.put("ext3", scProOrder.getOrderBusinessNo()); //生产编号
        recordMap.put("operateUser", user.getId());//当前操作人id
        customerRecordService.saveCustomerRecord(recordMap);//写入crm
        //暂缓时同步到CRM,新增渠道的订单不进行同步
        if (scProOrder.getOrderBusId() != null && !scProOrder.getOrderBusId().equals("")) {
            Map<String, Object> datas = new HashMap<>();
            datas.put("mainOrderId", scProOrder.getOrderId());//销售主订单id
            datas.put("childOrderId", scProOrder.getOrderBusId());//销售子订单id
            datas.put("orderStatus", "ORF_BDZT_4");//状态 ORF_BDZT_1:成单  ORF_BDZT_2 :退单   ORF_BDZT_3:废单  ORF_BDZT_4:暂缓   ORF_BDZT_5:生产中
            datas.put("currentUser",user);
            orderApiService.synOrderState(datas);
        }
        scProOrderTimeStateService.update_suspendScProOrderTime(scProOrder.getId()); //停止计算超期时间
    }

    /**
     * 添加协单人员
     *
     * @param id
     * @param userIds
     */
    public void addAssist(String id, String userIds) {
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        ScProOrder scProOrder = this.repository.get(ScProOrder.class, Long.valueOf(id));
        Assert.notNull(scProOrder, "没有查询到该生产订单的信息！");
        Assert.isTrue(scProOrder.getFlowUserId().equals(user.getId()), "只有流程人员才能进行该操作！");
        Assert.isTrue(scProOrder.getStatus().equals(ScStatusConstant.ORDER_PROCESS), "该生产订单状态已不再办理中,请刷新界面后操作!");
        String name = "";
        /*--------------获取协单人的名称和部门-----------*/
        if (userIds != "") {
            name = getAssistUserName(userIds);
        }
        scProOrder.setAssistUserId(userIds);
        scProOrder.setAssistUserName(name);
        DataWrap.updateWraps(scProOrder);

        //保存流程操作记录
        ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
        scProFlowOperating.setProProductId(scProOrder.getId());
        scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
        scProFlowOperating.setFlowUserId(user.getId());
        scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
        scProFlowOperating.setStatus(scProOrder.getStatus());
        scProFlowOperating.setOperation("添加协单人员");
        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_ADDASSIST);//添加协单人员
        DataWrap.saveWrap(scProFlowOperating);
        scProFlowOperating.setId(this.keyWorker.nextId());
        scProOrder.setFlowLatestOperationId(scProFlowOperating.getId()); //流程操作的最新id
        this.repository.save(scProFlowOperating);
        this.repository.saveOrUpdate(scProOrder);

    }

    /**
     * 获取协单人的名称部门并拼接成字符串
     *
     * @param userIds
     * @return
     */
    public String getAssistUserName(String userIds) {
        StringBuffer name = new StringBuffer();
        String[] idsStrArray = userIds.split(",");
        for (int i = 0; i < idsStrArray.length; i++) {
            String usid = idsStrArray[i];
            User user1 = this.repository.get(User.class, Long.valueOf(usid));
            OrganizationEntity organizationEntity = this.repository.get(OrganizationEntity.class, Long.valueOf(user1.getOrgId()));
            Assert.notNull(organizationEntity, "没有查询到[" + user1.getName() + "]的部门信息！");
            name.append(user1.getName().concat("(").concat(organizationEntity.getName()).concat(")").concat(","));
        }
        name = name.deleteCharAt(name.length() - 1);
        return String.valueOf(name);
    }
}
